package zl.ordermanager.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zl.ordermanager.dao.DeliveryDao;
import zl.ordermanager.dao.SalesOrderDao;
import zl.ordermanager.po.Tdelivery;
import zl.ordermanager.po.Tsalesorder;
import zl.ordermanager.service.DeliveryService;
import zl.ordermanager.utils.ConfigUtil;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.Delivery;
import zl.ordermanager.vo.PageHelper;
import zl.ordermanager.vo.SessionInfo;
import zl.ordermanager.vo.Total;

@Service
public class DeliveryServiceImpl implements DeliveryService {

	@Autowired
	private DeliveryDao deliveryDao;

	@Autowired
	private SalesOrderDao salesOrderDao;

	@Override
	public DataGrid<Delivery> dataGrid(HttpSession session, PageHelper pageHelper, Total total) {
		DataGrid<Delivery> dataGrid = new DataGrid<Delivery>();
		List<Delivery> deliveryList = new ArrayList<Delivery>();
		Map<String, Object> params = new HashMap<String, Object>();
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			params.put("keyword", "%%" + pageHelper.getKeywords() + "%%");
		}
		if (pageHelper.getSalesman() != null && !pageHelper.getSalesman().isEmpty()) {
			params.put("salesman", pageHelper.getSalesman());
		}
		if (pageHelper.getTechnician() != null && !pageHelper.getTechnician().isEmpty()) {
			params.put("technician", pageHelper.getTechnician());
		}
		if (pageHelper.getDriver() != null && !pageHelper.getDriver().isEmpty()) {
			params.put("driver", pageHelper.getDriver());
		}
		if (pageHelper.getAbstractMonth() != null && !pageHelper.getAbstractMonth().isEmpty()) {
			params.put("abstractMonth", pageHelper.getAbstractMonth());
		}
		if (pageHelper.getDeliveryMethod() != null && !pageHelper.getDeliveryMethod().isEmpty()) {
			params.put("deliveryMethod", pageHelper.getDeliveryMethod());
		}
		String hql = " from Tdelivery t ";
		String whereHql = whereHql(session, pageHelper);
		List<Tdelivery> tdeliveryList = deliveryDao.find(hql + whereHql + orderHql(pageHelper), params,
				pageHelper.getPageNum(), pageHelper.getNumPerPage());
		if (tdeliveryList != null && tdeliveryList.size() > 0) {
			for (Tdelivery tdelivery : tdeliveryList) {
				Delivery delivery = new Delivery();
				BeanUtils.copyProperties(tdelivery, delivery);
				deliveryList.add(delivery);
			}
		}
		dataGrid.setList(deliveryList);
		dataGrid.setTotal(deliveryDao.count("select count(*) " + hql + whereHql, params));

		total.setBonus(deliveryDao.sum("select sum(t.bonus) " + hql
				+ (whereHql.isEmpty() ? "where t.audit != null" : (whereHql + " and (t.audit != null)")), params));
		total.setCost(deliveryDao.sum("select sum(t.cost) " + hql
				+ (whereHql.isEmpty() ? "where t.audit != null" : (whereHql + " and (t.audit != null)")), params));
		return dataGrid;
	}

	private String whereHql(HttpSession session, PageHelper pageHelper) {
		String whereString = "";
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			whereString += "where (t.orderNo like :keyword ";
			whereString += " or t.orderDate like :keyword ";
			whereString += " or t.salesman like :keyword ";
			whereString += " or t.customer like :keyword ";
			whereString += " or t.product like :keyword ";
			whereString += " or t.deliveryMethod like :keyword ";
			whereString += " or t.deliveryDate like :keyword ";
			whereString += " or t.technician like :keyword ";
			whereString += " or t.departTime like :keyword ";
			whereString += " or t.returnTime like :keyword ";
			whereString += " or t.bonus like :keyword ";
			whereString += " or t.driver like :keyword ";
			whereString += " or t.driverPhone like :keyword ";
			whereString += " or t.cost like :keyword ";
			whereString += " or t.abstractMonth like :keyword ";
			whereString += " or t.remarks like :keyword)";
		}
		if (pageHelper.getSalesman() != null && !pageHelper.getSalesman().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.salesman = :salesman)";
			} else {
				whereString += " and (t.salesman = :salesman)";
			}
		}
		if (pageHelper.getTechnician() != null && !pageHelper.getTechnician().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.technician = :technician)";
			} else {
				whereString += " and (t.technician = :technician)";
			}
		}
		if (pageHelper.getDriver() != null && !pageHelper.getDriver().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.driver = :driver)";
			} else {
				whereString += " and (t.driver = :driver)";
			}
		}
		if (pageHelper.getAbstractMonth() != null && !pageHelper.getAbstractMonth().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.abstractMonth = :abstractMonth)";
			} else {
				whereString += " and (t.abstractMonth = :abstractMonth)";
			}
		}
		if (pageHelper.getDeliveryMethod() != null && !pageHelper.getDeliveryMethod().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.deliveryMethod = :deliveryMethod)";
			} else {
				whereString += " and (t.deliveryMethod = :deliveryMethod)";
			}
		}

		String userFilter = "";
		SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		if (sessionInfo != null) {
			if (sessionInfo.getRole().equals("业务员")) {
				userFilter = " (t.salesman = '" + sessionInfo.getRealname() + "')";
			}
		}

		if (!userFilter.isEmpty()) {
			if (!whereString.isEmpty()) {
				whereString = whereString + " and " + userFilter;
			} else {
				whereString = "where " + userFilter;
			}
		}

		return whereString;
	}

	private String orderHql(PageHelper pageHelper) {
		String orderString = "";
		if (pageHelper.getOrderField() != null && !pageHelper.getOrderField().isEmpty()
				&& pageHelper.getOrderDirection() != null && !pageHelper.getOrderDirection().isEmpty()) {
			orderString = " order by t." + pageHelper.getOrderField() + " " + pageHelper.getOrderDirection();
		}
		return orderString;
	}

	@Override
	public Delivery get(Integer id) {
		Tdelivery tdelivery = deliveryDao.get(Tdelivery.class, id);
		if (tdelivery == null) {
			return null;
		}
		Delivery delivery = new Delivery();
		BeanUtils.copyProperties(tdelivery, delivery);
		return delivery;
	}

	@Override
	public void add(Delivery delivery) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderNo", delivery.getOrderNo());
		params.put("technician", delivery.getTechnician());
		if (deliveryDao.count(
				"select count(*) from Tdelivery t where t.orderNo = :orderNo and t.technician = :technician", params) > 0) {
			throw new Exception("送货单已存在！");
		}
		Tdelivery tdelivery = new Tdelivery();
		BeanUtils.copyProperties(delivery, tdelivery);
		deliveryDao.save(tdelivery);
		params.clear();
		params.put("orderNo", delivery.getOrderNo());
		Tsalesorder tsalesorder = salesOrderDao.get("from Tsalesorder t where t.orderNo = :orderNo", params);
		if (tsalesorder != null) {
			tsalesorder.setDelivery("是");
		}
	}

	@Override
	public void edit(Delivery delivery) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderNo", delivery.getOrderNo());
		params.put("technician", delivery.getTechnician());
		if (deliveryDao.count(
				"select count(*) from Tdelivery t where t.orderNo = :orderNo and t.technician = :technician", params) > 0) {
			Tdelivery tdelivery = deliveryDao.get(
					"from Tdelivery t where t.orderNo = :orderNo and t.technician = :technician", params);
			if (tdelivery.getId().intValue() != delivery.getId().intValue()) {
				throw new Exception("送货单已存在！");
			}
		}
		Tdelivery tdelivery = deliveryDao.get(Tdelivery.class, delivery.getId());
		BeanUtils.copyProperties(delivery, tdelivery);
	}

	@Override
	public void delete(Integer id) {
		Tdelivery tdelivery = deliveryDao.get(Tdelivery.class, id);
		deliveryDao.delete(tdelivery);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderNo", tdelivery.getOrderNo());
		Tsalesorder tsalesorder = salesOrderDao.get("from Tsalesorder t where t.orderNo = :orderNo", params);
		if (tsalesorder != null) {
			tsalesorder.setDelivery("否");
		}
	}

	@Override
	public void audit(HttpSession session, Integer id) throws Exception {
		Tdelivery tdelivery = deliveryDao.get(Tdelivery.class, id);
		SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
        if (sessionInfo.getRole().equals("管理员") || sessionInfo.getRole().equals("财务")) {
            tdelivery.setAudit(sessionInfo.getRealname());
            deliveryDao.save(tdelivery);
        } else if (sessionInfo.getRole().equals("业务员")) {
            if (sessionInfo.getRealname().equals(tdelivery.getSalesman())) {
                tdelivery.setAudit(sessionInfo.getRealname());
                deliveryDao.save(tdelivery);
            } else {
                throw new Exception("只能审核属于自己的送货单！");
            }
        }
	}

}
